﻿using MainView.Model;
using MainView.Model.sys;
using MainView.MyControl;
using S7.Net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MainView
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        public static string roomStr { get; private set; } = MainView.Properties.Settings.Default.roomStr;
        public static int roomNum { get; private set; } = MainView.Properties.Settings.Default.roomNum;

        public static string ZRIP { get; private set; } = MainView.Properties.Settings.Default.zrIP;
        public static string XDIP { get; private set; } = MainView.Properties.Settings.Default.xdIP;
        public static string HQIP { get; private set; } = MainView.Properties.Settings.Default.hqIP;
        public static string HHIP { get; private set; } = MainView.Properties.Settings.Default.hhIP;      

        public static string zrIP = ZRIP;
        public static string xdIP = XDIP;
        public static string hqIP = HQIP;
        public static string hhIP = HHIP;


        static Plc zrPlc= new Plc(CpuType.S71200, zrIP, 0, 1);
        static Plc xdPlc = new Plc(CpuType.S71200, xdIP, 0, 1);
        static Plc hqPlc = new Plc(CpuType.S71200, hqIP, 0, 1);
        static Plc hhPlc = new Plc(CpuType.S71200, hhIP, 0, 1);

        private void MainForm_Load(object sender, EventArgs e)
        {
            UPRoomState();
            try
            {
                flowLayoutPanel1.Controls.Clear();
                foreach (var Th in RoomState.RoomStateDic)
                {
                    flowLayoutPanel1.Controls.Add(Th.Value.devCommon);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Task t = new Task(() =>
            {
                GetOnline(0, zrPlc);
                GetOnline(3, xdPlc);
                GetOnline(4, hqPlc);
                GetOnline(5, hhPlc);
            });
            t.Start();
            
            for(int i=0;i<6;i++) RoomState.RoomStateDic[i].devCommon.UpChangePic(i);        
        }
        /// <summary>
        /// 通过ID连接PLC来判断房间是否在线，并做出相应的显示
        /// </summary>
        /// <param name="id"> 房间号 </param>
        /// <param name="plc"> 每个房间PLC连接的实例化 </param>
        private void GetOnline(int id, Plc plc)
        {
            if (!plc.IsConnected)
            {
                try
                {
                    ErrorCode errorCode = plc.Open();
                    if (errorCode == ErrorCode.NoError)
                    {
                        RoomState.RoomStateDic[id].devCommon.UpShowOnline(true);
                        RoomOper.RoomOperDic[id].devOper.UpShowOnline(true, 1);
                    }
                    else
                    {
                        RoomState.RoomStateDic[id].devCommon.UpShowOnline(false);
                        RoomOper.RoomOperDic[id].devOper.UpShowOnline(false, 0);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("连接PLC失败！");
                    RoomState.RoomStateDic[id].devCommon.UpShowOnline(false);
                    RoomOper.RoomOperDic[id].devOper.UpShowOnline(false, 0);
                }

            }
        }

        public static void GetEnv(int id, Plc plc)//可用于整容间以及火化后厅
        {
            byte[] statArray = new byte[1];
            //0号整容间、5号火花后厅
            int UV = 0;  //Q0.0对应消毒
            int ZM = 1;  //Q0.1对应照明
            int FAN = 2; //Q0.2对应新风
            int FLUE = 3;//Q0.3对应排风
            try
            {
                statArray = plc.ReadBytes(DataType.Output, 0, 0, 1);
                byte stat = statArray[0];
                //Q0.0为开，对应为：消毒
                switch (id)
                {
                    case 3://3号消毒间
                        UV = 5;      //Q0.5对应消毒
                        ZM = 6;      //Q0.6对应照明
                        FAN = 0;     //Q0.0对应新风
                        FLUE = 1;    //Q0.1对应排风
                        break;
                    case 4: // 火花前厅
                        UV = 1;     //Q0.1对应消毒
                        ZM = 0;     //Q0.0对应照明
                        FAN = 2;    //Q0.2对应新风
                        FLUE = 3;   //Q0.3对应排风
                        break;
                    default:
                        break;
                }

                RoomState.RoomStateDic[id].devCommon.UpShowUV(stat.SelectBit(UV));
                RoomOper.RoomOperDic[id].devOper.UpShowUV(stat.SelectBit(UV));

                RoomState.RoomStateDic[id].devCommon.UpShowLight(stat.SelectBit(ZM));
                RoomOper.RoomOperDic[id].devOper.UpShowLight(stat.SelectBit(ZM));

                RoomState.RoomStateDic[id].devCommon.UpShowFan(stat.SelectBit(FAN));
                RoomOper.RoomOperDic[id].devOper.UpShowFan(stat.SelectBit(FAN));

                RoomState.RoomStateDic[id].devCommon.UpShowFlue(stat.SelectBit(FLUE));
                RoomOper.RoomOperDic[id].devOper.UpShowFlue(stat.SelectBit(FLUE));
               
                if (id == 0) RoomState.RoomStateDic[id].devCommon.UpShowSpeed(PLC.Form1.zrSpeed);
                if (id == 5) RoomState.RoomStateDic[id].devCommon.UpShowSpeed(PLC.Form1.hhSpeed);
                PLC.Form1.zrSpeed = 0;
                PLC.Form1.hhSpeed = 0;
            }
            catch (Exception ex)
            {
                RoomState.RoomStateDic[id].devCommon.UpShowOnline(false);
                plc.Close();
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// 更新房间名及状态
        /// </summary>
        public static void UPRoomState()
        {
            RoomState.RoomStateDic.Clear();          
            string[] roomName = new string[roomNum];
            try
            {
                roomName = roomStr.Split(',');
                for (int i = 0; i < 6; i++)
                {
                    var id = i;
                    var addr = i.ToString();
                    var name = roomName[i];
                    RoomState.RoomStateDic.Add(id, new RoomState(id, addr, name));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);               
            }
        }

        /// <summary>
        /// 更新时钟显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            ucledTime1.Value = DateTime.Now;           
        }
        /// <summary>
        /// 定时获取房间的设备状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            if (RoomState.RoomStateDic[0].devCommon.isOnline) GetEnv(0, zrPlc);
            if (RoomState.RoomStateDic[3].devCommon.isOnline) GetEnv(3, xdPlc);
            if (RoomState.RoomStateDic[4].devCommon.isOnline) GetEnv(4, hqPlc);
            if (RoomState.RoomStateDic[5].devCommon.isOnline) GetEnv(5, hhPlc);        
        }

        private void button2_Click(object sender, EventArgs e)
        {
            GetOnline(0, zrPlc);
            GetOnline(3, xdPlc);
            GetOnline(4, hqPlc);
            GetOnline(5, hhPlc);
        }

        int timerCount = 0;

        private void timer3_Tick(object sender, EventArgs e)
        {
            timerCount++;
            if (timerCount == 5)//5min 到达
            {
                timerCount = 0;
                GetOnline(0, zrPlc);
                GetOnline(3, xdPlc);
                GetOnline(4, hqPlc);
                GetOnline(5, hhPlc);
            }
        }
        private void CloseAll(Plc plc)
        {
            byte[] value = new byte[1];
            value[0] = 0x00;
            plc.WriteBytes(DataType.Output, 0, 0, value);
        }

        private void btnEnv_Click(object sender, EventArgs e)
        {
            CloseAll(zrPlc);
            CloseAll(xdPlc);
            CloseAll(hqPlc);
            CloseAll(hhPlc);
        }
        /// <summary>
        /// 给PLC按位写入
        /// </summary>
        /// <param name="id"></param>
        /// <param name="bit"></param>
        /// <param name="state"></param>
        public static void SetBits(int id,int bit,bool state)
        {
            byte[] stat = new byte[1];
            Plc plc = new Plc(CpuType.S71200, zrIP, 0, 1);
            if (id == 0) plc = zrPlc;
            if (id == 3) plc = xdPlc;
            if (id == 4) plc = hqPlc;
            if (id == 5) plc = hhPlc;
            try
            {                
                stat = plc.ReadBytes(DataType.Output, 0, 0, 1);
                if (state)stat[0] = (byte)(stat[0] | (1 << bit));                                         
                else stat[0] = (byte)(stat[0] & (~(1 << bit)));               
                plc.WriteBytes(DataType.Memory, 0, 0, stat);
                
            }
            catch (Exception ex)
            {
                Console.WriteLine("设置错误"+ex.ToString());
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}
